package com.system.manager.modules.authorized.controller;


import com.system.manager.common.annotation.Anonymous;
import com.system.manager.common.annotation.CurrSubject;
import com.system.manager.common.annotation.PreAuthorize;
import com.system.manager.common.entity.PageDTO;
import com.system.manager.common.entity.Result;
import com.system.manager.common.exception.SysException;
import com.system.manager.modules.authorized.entity.AuthenticationResultDTO;
import com.system.manager.modules.authorized.entity.Subject;
import com.system.manager.modules.authorized.entity.User;
import com.system.manager.modules.authorized.enums.AuthorizationErrorCode;
import com.system.manager.modules.authorized.enums.SubjectType;
import com.system.manager.modules.authorized.service.IUserService;
import com.system.manager.modules.authorized.vo.LoginUser;
import com.system.manager.modules.authorized.vo.PasswordVo;
import com.system.manager.modules.authorized.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yxp
 * @since 2021-10-18
 */
@Api(tags = "用户API")
@Slf4j
@Validated
@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private IUserService userService;

    @Anonymous
    @ApiOperation("用户登陆")
    @PostMapping("login")
    public Result login(@RequestBody LoginUser loginUser){
        // 1.登陆操作
        AuthenticationResultDTO token = userService.login(loginUser);

        return Result.ok(token);
    }


    @ApiOperation("验证token")
    @GetMapping("check/token")
    @PreAuthorize({SubjectType.ANONYMOUS})
    public Result checkToken(){
        return Result.ok();
    }

    @ApiOperation("获取所有的用户")
    @PreAuthorize(SubjectType.SYSTEM_ADMIN)
    @GetMapping("select/list/page/old")
    public PageDTO selectUsers(@RequestParam(name = "page", required = false, defaultValue = "1")Integer page,
                              @RequestParam(name = "limit", required = false, defaultValue = "10")Integer size){
        // 根据分页查询出所有的用户
        PageDTO<User> pageDTO = userService.selectUsers(page, size);

        return pageDTO;
    }


    @ApiOperation("根据条件查询出当前的用户")
    @PreAuthorize(SubjectType.SYSTEM_ADMIN)
    @GetMapping("select/list/page")
    public PageDTO selectUsers(@RequestParam(name = "page", required = false, defaultValue = "1")Integer page,
                               @RequestParam(name = "limit", required = false, defaultValue = "10")Integer size,
                               @RequestParam(name = "role", required = false)Integer role,
                               @RequestParam(name = "name",required = false)String name,
                               @RequestParam(name = "phone",required = false)String phone,
                               @RequestParam(name = "userAccount", required =false)String userAccount){
        // 根据分页查询出所有的用户
        PageDTO<User> pageDTO = userService.selectUsersCondition(page, size, role,userAccount, name, phone);

        return pageDTO;
    }

    @PreAuthorize({SubjectType.SYSTEM_ADMIN, SubjectType.ENTERPRISE_ADMIN})
    @ApiOperation("增加用户")
    @PostMapping("insert")
    public Result insert(@RequestBody UserVo userVo){

        try {
            // 1.登陆操作
            // 新建用户
            User user = new User();
            BeanUtils.copyProperties(userVo,user);
            userService.insert(user);

            return Result.ok();
        } catch (SysException e) {
            e.printStackTrace();
            return Result.error(e);
        }

    }

    @PreAuthorize({SubjectType.SYSTEM_ADMIN, SubjectType.ENTERPRISE_ADMIN})
    @ApiOperation("删除用户")
    @GetMapping("delete/{userId}")
    public Result delete(@PathVariable("userId")Integer userId){

        try {
            userService.removeById(userId);

            return Result.ok();
        } catch (SysException e) {
            e.printStackTrace();
            return Result.error(e);
        }

    }

    @PreAuthorize({SubjectType.SYSTEM_ADMIN, SubjectType.ENTERPRISE_ADMIN})
    @ApiOperation("查询用户信息")
    @GetMapping("select/{userId}")
    public Result selectById(@PathVariable("userId")Integer userId){

        try {
            User user = userService.getById(userId);

            return Result.ok(user);
        } catch (SysException e) {
            e.printStackTrace();
            return Result.error(e);
        }

    }


    @PreAuthorize({SubjectType.SYSTEM_ADMIN, SubjectType.ENTERPRISE_ADMIN})
    @ApiOperation("修改用户信息")
    @PostMapping("save")
    public Result save(@RequestBody User user){

        try {
            userService.updateById(user);

            return Result.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }

    }

    @PreAuthorize({SubjectType.SYSTEM_ADMIN, SubjectType.ENTERPRISE_ADMIN,SubjectType.RISK_ADMIN})
    @PostMapping("import")
    @ApiOperation("导入用户信息")
    public Result importUser(@RequestParam("file") MultipartFile file){

        try {
            String filename = file.getOriginalFilename();
            log.info("---->当前文件的文件名：" + filename);
            InputStream tps = (file.getInputStream());


            // 获取poml对象，用以操作excl表
            final XSSFWorkbook tpWorkbook = new XSSFWorkbook(tps);

            // 导入文件
            boolean success = userService.importUser(tpWorkbook);

        } catch (IOException e) {
            e.printStackTrace();
            return Result.error();
        }catch (SysException sysE){
            return Result.error(sysE);
        }
        return Result.ok();
    }

    @PreAuthorize(SubjectType.ANONYMOUS)
    @ApiOperation("用户修改密码")
    @PostMapping("update/password")
    public Result updatePassword(@RequestBody PasswordVo passwordVo, @CurrSubject Subject subject){

        boolean isSame = userService.updatePassword(passwordVo.getOldPassword(), passwordVo.getNewPassword(), passwordVo.getAgainPassword(), subject.getId());

        if(!isSame){
            return Result.error(AuthorizationErrorCode.PSWD_NOT_SAME);
        }

        return Result.ok();
    }
}
